﻿using System.IO;
using System.Reflection;
using System.Linq;
using System;

namespace Flexible.Framework
{
    class Program
    {
        static string startupPath;
        static string pluginsPath;
        static string settingsPath;
        static string startListPath;

        static PluginManager manager;

        [STAThread]
        static void Main()
        {
            Init();

            LoadPlugins();

            LoadAutoStart();

            manager.Run();

            SaveAutoStart();

            Console.ReadKey();
        }

        private static void SaveAutoStart()
        {
            using (FileStream stream = File.OpenWrite(startListPath))
                manager.SaveAutostartList(stream);
        }

        private static void LoadAutoStart()
        {
            using (FileStream stream = File.OpenRead(startListPath))
                manager.LoadAutostartList(stream);
        }

        private static void LoadPlugins()
        {
            foreach (string dllPath in Directory.GetFiles(pluginsPath, "*.dll"))
            {
                Assembly assembly = Assembly.LoadFile(dllPath);
                var activators = manager.SearchAssembly(assembly).ToList();
                foreach (var activator in activators)
                {
                    manager.Register(activator);
                }
            }
        }

        private static void Init()
        {
            startupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            pluginsPath = Path.Combine(startupPath, "plugins");
            if (!Directory.Exists(pluginsPath))
                Directory.CreateDirectory(pluginsPath);
            settingsPath = Path.Combine(startupPath, "settings");
            if (!Directory.Exists(settingsPath))
                Directory.CreateDirectory(settingsPath);
            startListPath = Path.Combine(startupPath, @"settings\autostart");

            manager = new PluginManager(new SettingsStreamer(settingsPath));
        }
    }
}
